package com.situ.allaia.api;

import com.situ.allaia.model.AdminUser;
import com.situ.allaia.model.User;
import com.situ.allaia.model.UserSearchBean;
import com.situ.allaia.service.UserService;
import com.situ.allaia.util.PaginateInfo;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/users",produces = "application/json;charset=utf-8")
public class UserApi {
    private final UserService userService;

    public UserApi(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public Map<String,Object> findAll(UserSearchBean usb, @RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "10")Integer limit){
        PaginateInfo pi = new PaginateInfo(page,limit);
        List<User> userList = userService.findAll(usb,pi);
        return Map.of("code",0,"msg","","count",pi.getTotal(),"data",userList);
    }

    @PostMapping
    public Map<String,Object> save(User user){
        //参数校验
        if (!StringUtils.hasText(user.getUsername())){
            return Map.of("success",false,"error","用户名不允许为空");
        }
        if (!StringUtils.hasText(user.getPassword())){
            return  Map.of("success",false,"error","密码不允许为空");
        }
        boolean success = userService.save(user);
        if (success){
            return Map.of("success",true,"data",user);
        }else{
            return Map.of("success",false,"error","修改后台用户失败");
        }
    }


    @PutMapping
    public Map<String, Object> edit(User user) {
        //todo：参数校验
        boolean success = userService.update(user);
        if (success) {
            return Map.of("success", true, "data", user);
        } else {
            return Map.of("success", false, "error", "修改后台用户失败");
        }
    }


    @DeleteMapping
    public Map<String, Object> deleteByIds(Integer[] ids) {
        //todo：参数校验
        if (ids == null || ids.length == 0) {
            return Map.of("success", false, "error", "未提交要删除的记录编号");
        }

        int rows = userService.deleteByIds(ids);


        if (rows > 0) {
            return Map.of("success", true, "rows", rows);
        } else {
            return Map.of("success", false, "error", "未删除任何记录");
        }
    }
}
